import os, sys

class OsBackend():
    """ Interface for OS commands
        
    This class will provide the interface to the os for the three types of os calls.
    
    local calls - os calls that are made on the OS that flyback is running on
    backup source calls - os calls that are made on the OS that flyback is backing up from
    backup destination calls - os calls that are made on the OS that flyback is backing up to
    """
    
    def get_run_from_dir(self):
        return os.path.abspath(os.path.dirname(sys.argv[0])) + '/'
    
    def get_home_directory(self):
        return os.path.expanduser("~")
    
    def get_directory_list(self, directory):
        return os.listdir(directory)
    
    def is_path_a_directory(self, path):
        return os.path.isdir(path)
    
    def is_path_a_file(self, path):
        return os.path.isfile(path)
    
    def join(self, a, *p):
        return os.path.join(a, *p)
        
    def get_stat(self, filename):
        return os.stat(filename)
    
    def delete_file(self, filename):
        os.remove(filename)
        
    def touch_file(self, filename):
        f = open(filename,'w')
        # f.write('delete this if FlyBack has crashed/been killed and refuses to start a new backup.\n')
        f.close()
        
    def get_free_space(self, parent_backup_dir):
        stdin, stdout = os.popen4( 'df -P %s' % parent_backup_dir )
        return int(stdout.readlines()[1].split()[3]) # in KB

    def shell_command(self, cmd):
        """ shell an os command
        executes a command on the os this class is pointed at
        
        cmd
            the command to execute
            
        returns (stdin, stdout, stderr)
        
        """
        return os.popen3(cmd)